<template>
  <div>
    <p class="f18 mb24">商品详情信息 <span class="f12" style="color: #86909c">（支持编辑图片、文本、表格、多样化）</span></p>

    <div style="border: 1px solid #ccc">
      <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="'default'" />
      <Editor
        style="height: 500px; overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="'simple'"
        @onCreated="handleCreated"
      />
    </div>

    <!-- <el-button type="primary" @click="getEditor">获取富文本编辑器数据</el-button> -->
  </div>
</template>

<script setup>
import { ref, watch, shallowRef, onBeforeUnmount, onMounted } from "vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { getFolder } from "@/utils/index";
import { getRichText, saveRichText } from "@/apis/products/specifications";

const _optionInfo = ref({});

const props = defineProps({
  optionInfo: {
    type: Object,
    default: () => {}
  }
});

onMounted(() => {});
watch(
  () => props.optionInfo,
  async val => {
    if (val) {
      if (val.actionType === "edit" || val.actionType === "copy" || val.actionType === "re-applay") {
        _optionInfo.value = JSON.parse(JSON.stringify(val));
        if (val.actionType === "copy") {
          valueHtml.value = _optionInfo.value.editDetailInfo.shopDetail;
        } else {
          let params = { sourceType: 6, sourceId: _optionInfo.value.editDetailInfo.collectId };
          if (_optionInfo.value.editDetailInfo.sourceType === 1) {
            // 选品过来的商品
            params = { sourceType: 5, sourceId: _optionInfo.value.editDetailInfo.productId };
          }
          getRichText(params).then(res => {
            if (res.code === 200) {
              valueHtml.value = res.data.content;

              //如果是选品过来的商品，禁用富文本编辑器
              if (props.optionInfo?.editDetailInfo?.sourceType === 1) {
                editorRef.value.disable();
              }
            }
          });
        }
      }
    }
  },
  { deep: true }
);

const saveRichTextFun = () => {
  saveRichText({ sourceType: 6, sourceId: _optionInfo.value.editDetailInfo.collectId, content: valueHtml.value }).then(res => {
    if (res.code === 0) {
      console.log("富文本详情修改成功");
    }
  });
};

//====================================富文本编辑器========================================================================================
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
const toolbarConfig = {
  excludeKeys: ["fullScreen"] //配置不显示的菜单-上传图片、上传视频 "group-image", "group-video",
  // toolbarKeys: ["uploadImage", "uploadVideo"] //配置想要显示的菜单
};
const editorConfig = {
  placeholder: "请输入内容...",
  pointerEvents: "none",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file, insertFn) => {
        // console.log("触发图片上传");
        await handleAvatarChangeIcon(file);
        // console.log("上传图片的地址===", imgUrl.value);
        imgUrl.value && insertFn(imgUrl.value.split("?")[0]); // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
      }
    },
    uploadVideo: {
      customUpload: async (file, insertFn) => {
        // console.log("触发视频上传");
        await handleAvatarChangeIcon(file, "video");
        console.log("上传视频的地址===", videoUrl.value);
        videoUrl.value && insertFn(videoUrl.value.split("?")[0]); // 最后插入视频 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填
      }
    }
  }
};
// const currentObj = ref({}); //当前点击的对象，用于富文本编辑器值的赋值
const imgUrl = ref(""); //编辑器每选择一次图片，上传后的地址
const videoUrl = ref(""); //编辑器每选择一次视频，上传后的地址

//为富文本编辑器添加key值，解决编辑成功后又重新打开时报错的问题
// const selectedContent = computed(() => {
//     return String(new Date().getTime()) + dialogEditorVisible.value;
// });

const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

//====================================文件上传========================================================================================

import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
import { ElMessage } from "element-plus";
const ossStore = useMultipartOssStore();

const handleAvatarChangeIcon = async (file, type = "img") => {
  //选中文件触发的change事件
  // console.log(file);

  if (type === "video") {
    const flag = await fileType(type, [file]);

    if (!flag) {
      ElMessage({
        message: "只能上传视频文件，并且视频时长不超过5分钟，大小不超过500M",
        type: "error",
        offset: 60
      });
      videoUrl.value = ""; //视频校验失败，清空视频地址
      return;
    }
  }

  await customUpload({ file }, type);
};
/**
 * 校验文件类型
 */
const fileType = async (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!((item.type === "image/jpeg" || item.type === "image/png") && item.size <= 1024 * 1024 * 5)) {
        flag = false;
      }
      if (!(item.type === "image/jpeg" || item.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      console.log("视频的大小===", item);
      if (!(item.type === "video/mp4" && item.size <= 1024 * 1024 * 500)) {
        flag = false;
      }
      if (item.type === "video/mp4") {
        await getTimes(item);
        // console.log("视频的时长===", item.raw.size <= 1024 * 1024 * 100, videoTime.value);
        if (!(videoTime.value <= 5 * 60)) {
          flag = false;
        }
      }
    }
  }
  return flag;
};
/**
 * 获取视频时间长度
 */
const videoTime = ref(0);
const getTimes = async file => {
  let content = file;
  //获取录音时长
  let url = URL.createObjectURL(content);
  //经测试，发现audio也可获取视频的时长
  let audioElement = new Audio(url);
  console.log(2222);
  await new Promise((resolve, reject) => {
    audioElement.addEventListener("loadedmetadata", _event => {
      //保存获取时间长度
      videoTime.value = parseInt(audioElement.duration);
      resolve("时长获取成功");
    });
  });
};
/**
 * 上传
 */
const getFileName = name => {
  const arr = name.split(".");
  const _arr = JSON.parse(JSON.stringify(arr));
  let _name = "";
  let _suffix = "";
  if (arr.length > 2) {
    _arr.splice(_arr.length - 1, 1);
    _name = _arr.join(".");
    _suffix = arr[arr.length - 1];
  } else {
    _name = arr[0];
    _suffix = arr[1];
  }
  const folder = getFolder();
  return folder + _name + new Date().getTime() + "." + _suffix;
};
const customUpload = async (option, type) => {
  const objName = getFileName(option.file.name);
  await ossStore
    .submit(objName, option.file)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl);
      if (type === "img") {
        imgUrl.value = res.fileUrl.split("?")[0];
      } else {
        videoUrl.value = res.fileUrl.split("?")[0];
      }
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};

const getEditor = () => {
  return new Promise((resolve, reject) => {
    console.log("富文本===", valueHtml.value);
    resolve({
      valueHtml: valueHtml.value
    });
  });
};
defineExpose({
  getEditor,
  saveRichTextFun
});
</script>

<style lang="scss" scoped>
:deep(.w-e-textarea-video-container) {
  video {
    width: 100% !important;
  }
}
</style>
